<template>
    <div id="role">
       <!-- 搜索栏 -->
       <el-card id="search">
            <el-row>
                <el-col :span="20">
                    <el-input v-model="searchModel.roleName" placeholder="角色名称"  clearable style="width: 200px;" class="filter-item"></el-input> <!-- style="width: 200px;" class="filter-item"   换行否 -->
                   
                    <el-button @click="getRoleList()" type="primary" round   icon="el-icon-search">查询</el-button>
                </el-col>
                <el-col :span="3"> <!-- span  3  左右位置 -->
                <el-button @click="openEditUI(null)" type="primary" icon="el-icon-plus" circle></el-button>
                </el-col>
            </el-row>
        </el-card>

         <!-- --------------------------------------------结果列表 --------------------------------->
        <el-card>
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
            <el-table-column  label="序号">
            <template v-slot="scope">
                {{ (searchModel.pageNo-1)*searchModel.pageSize + scope.$index + 1 }}
            </template>
            </el-table-column>
            <el-table-column prop="roleId" label="角色ID"width="200" ></el-table-column>
            <el-table-column prop="roleName" label="角色名称" width="260"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="openEditUI(scope.row.roleId)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
            </el-table>
        </el-card>
        <!-- --------------------------------------------结果列表 --------------------------------->
       


      <!--分页组件 -->
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchModel.pageNo"
        :page-sizes="[5,10,20,50]"
        :page-size="searchModel.pageSize"
        layout="total,sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
         <!--分页组件 -->
         <!-- 新增标签弹层 -->
        <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
            <el-form ref="roleFormRef" :model="formData"  :rules="rules" label-position="right" label-width="100px">

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="角色名称" prop="roleName">
                                <el-input v-model="formData.roleName"></el-input>

                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="角色描述" prop="roleDesc">
                                <el-input v-model="formData.roleDesc"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="权限设置" prop="menuIdList">
                               <el-tree :data="menuList" 
                               :props="menuProps" 
                               show-checkbox
                               default-expand-all 
                               node-key="menuId"
                               ref="menuRef" 
                               style="width: 85%;"></el-tree>
                            </el-form-item>
                   
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel()">取消</el-button>
                    <el-button type="primary" @click="saveRole()">确定</el-button>
            </div>
        </el-dialog>  
        <!---------------- 新增标签弹层-------------------- -->     
    </div>
</template>

<script>
// 导入接口
import roleManageAPI from '@/api/roleManage'
import menuAPI       from '@/api/menuManage'
export  default{
    data() {
            return {
                menuList: [],
                menuProps:{
                  children: "children",
                  label: "title"
                },
                dialogFormVisible: false,//添加表单是否可见
                dialogFormVisible4Edit:false,//编辑表单是否可见
                formData: {},//表单数据
                total: 0,
                searchModel:{
                    pageNo: 1,
                    pageSize: 10
                },
              
                dataList: [],  //当前页要展示的列表数据
                rules: {// 校验规则
                roleName: [{ required: true, message: '角色为必填项', trigger: 'blur' }],
                roleDesc: [{ required: true, message: '角色描述为必填项', trigger: 'blur' }]
                }
            }

        },
        methods:{
            getAllMenu(){
                menuAPI.getAllMenu().then(response =>{
                    this.menuList= response.data;
                });
            },
           //添加    -- this.$refs.roleFormRef.validate((valid)=>{ ---数据验证
           saveRole() {
                //触发表单验证
                this.$refs.roleFormRef.validate((valid)=>{ 
                    if(valid){
                        let getCheckedKeys = this.$refs.menuRef.getCheckedKeys();
                        let getHalfCheckedKeys = this.$refs.menuRef.getHalfCheckedKeys();
                       this.formData.menuIdList = getCheckedKeys.concat(getHalfCheckedKeys); // 将选中的 menuId 赋值给 formData.menuIdList
                       //console.log(this.formData.menuIdList);
                        // 提交请求给后台
                        roleManageAPI.saveRole(this.formData).then(response =>{
                        // 成功提示
                        this.$message.success(response.msg);
                        //this.$message({
                        //message:response.msg,
                        //type: 'success'
                       // });
                      //修改成功关闭窗口   false
                        this.dialogFormVisible = false;   
                        this.clearForm = true;
                        // 刷新表格
                        this.getRoleList();
                        })
                    }else{
                        console.log("error submit!!");
                        return false;
                    }
                
                });
            },
            // 删除
            handleDelete(role) {
                
                this.$confirm("次操作永久删除，是否继续？", "提示", {   //confirm  防手抖
                    type: "info"
                }).then(() => {
                    roleManageAPI.delleterole(role.roleId).then(response =>{
                        //console.log("success!")
                        if (response.msg=='success') { //判断当前操作是否成功
                            this.$message.success("删除成功！");
                        } else {
                            this.$message.error("数据同步失败,自动刷新");
                        }
                    }).finally(() => {
                        //2.重新加载数据
                        this.getRoleList();
                    });
                }).catch(() => {
                    this.$message.info("取消操作");
                });
            },

            //弹出编辑窗口
            handleUpdate(role) {    //20240510
            // 提交请求给后台   role.roleId
            roleManageAPI.getroleById(role.roleId).then(response =>{
            if (response.msg === 'success' && response.data != null) {
                     this.dialogFormVisible = true;
                     this.formData = response.data;
                    } else {
                        this.$message.error("数据同步失败,自动刷新");
                    }
                }).finally(() => {
                    //2.重新加载数据
                    this.getRoleList();
                });  
          
            },
            
            //查询所有
            getRoleList(){
            roleManageAPI.getRoleList(this.searchModel).then(response=>{ 
             this.dataList=response.data.rows;
             this.total=response.data.total;
             
            });
           },
           //分页
           handleSizeChange(pageSize){
            this.searchModel.pageSize=pageSize
            this.getRoleList();
           },
           handleCurrentChange(pageNo){
            this.searchModel.pageNo=pageNo
            this.getRoleList();
           },
          
            //弹出添加窗口
            openEditUI(id) {
                if( id==null){
                this.title='新增角色'
                }else{
                    this.title='修改角色'
                    //根据id查找角色
                    roleManageAPI.getroleById(id).then(response=>{ 
                        this.formData=response.data
                        this.$nextTick(() => {
                        if (this.$refs.menuRef) {
                                this.$refs.menuRef.setCheckedKeys(response.data.menuIdList);
                                    }
                                });
                        });
                } 
                this.dialogFormVisible = true;
                this.clearForm(); // 清空表单数据
            },
            //取消
            cancel() {
                this.dialogFormVisible = false;
                this.$message.success("操作取消！");
            },
           

            //重置表单
            clearForm() {
                this.formData = {};
                this.$refs.roleFormRef.clearValidate();
                this.$refs.menuRef.setCheckedKeys([]);         
            },
        },
        
        //钩子函数，VUE对象初始化完成后自动执行
        created(){
            this.getRoleList();
            this.getAllMenu();
        }
};
</script>
<style>
#search .el-input__inner {
    width: 200px;
    margin-right: 10px;
}
</style>
